import {defineStore} from "pinia";
import {UserInfo} from '@/types/store/user.ts'
import { loginApi } from '@/api/login.ts';
import {LoginParams} from "@/api/user/model";
import {TOKEN_KEY} from '@/enums/CacheEnum'
import { store } from "@/store";
import UserAPI from "@/api/user";
import { resetRouter } from "@/router";

export const useUserStore = defineStore('user',()=>{
    const user = ref<UserInfo>({
        roles:[],
        perms:[]
    })


    /**
     * 登录调用
     * @param {LoginParams}
     * @returns
     */
    const login = async (loginParams: LoginParams): Promise<void> => {
        try {
            const data = await loginApi(loginParams);
            const { tokenType, accessToken } = data.data;
            localStorage.setItem(TOKEN_KEY, tokenType + ' ' + accessToken);
            return;
        } catch (error) {
            throw error;
        }
    }

    /**
     * 获取用户信息（昵称、头像、角色集合、权限集合）
     */
    const getUserInfo = async (): Promise<UserInfo> => {
        try {
            const data = await UserAPI.getInfo();
            if (!data) {
                throw new Error("验证失败，请重新登录。");
            }
            if (!data.roles || data.roles.length <= 0) {
                throw new Error("错误：角色必须是非null数组！");
            }
            Object.assign(user.value, {...data});
            return data;
        } catch (err) {
            throw err;
        }
    }

    /**
     * 清空路由
     */
    const resetToken = () =>{
        return new Promise<void>((resolve)=>{
            localStorage.setItem(TOKEN_KEY,"")
            resetRouter();
            resolve()
        })
    }

    return {user,login,getUserInfo,resetToken}
},{
    persist: true,
})

// 非setup
export const useUserStoreHook = () => {
    return useUserStore(store);
  }